﻿// Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
// 作者:吕艳阳

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Runtime.Caching;
using System.Windows.Forms;
using XCI.Core;
using XCI.Helper;
using XCI.Sys.Forms;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;

namespace XCI.Sys
{
    /// <summary>
    /// 权限子系统应用处理器
    /// </summary>
    public class SysAppHandler : AppHandler
    {
        #region Overrides of AppHandler

        public override Type GetSplashScreenType()
        {
            return typeof(FrmImageSplashScreen);
        }

        /// <summary>
        /// 获取数据字典
        /// </summary>
        /// <param name="code">字典编码</param>
        /// <returns>返回指定编码的数据字典</returns>
        public override Dic GetDic(string code)
        {
            return SysDicService.Instance.GetDicListFromCache(code);
        }

        /// <summary>
        /// 创建应用服务器对象
        /// </summary>
        public override WebApiClient CreateWebApiClient(WebApiConfig config)
        {
            return new SysWebApiClient(config);
        }

        /// <summary>
        /// 创建文件应用服务器对象
        /// </summary>
        public override WebApiClient CreateFileWebApiClient(WebApiConfig config)
        {
            return new SysWebFileApiClient(config);
        }

        /// <summary>
        /// 是否有指定模块编码的权限
        /// </summary>
        /// <param name="codes">模块编码集合</param>
        /// <returns>存在返回true,否则返回false</returns>
        public override bool Permit(params string[] codes)
        {
            if (SysApp.CurrentUser == null) return false;
            if (SysApp.CurrentUser.IsAdmin) return true;
            if (codes == null || codes.Length == 0) return false;
            var cacheObject = MemoryCache.Default.Get(R.CurrentUserOwnModulesMapCacheKey);
            if (cacheObject == null)
            {
                var modules = SysApp.GetCurrentUserOwnModules();
                var map = new Dictionary<string, SysModule>(modules.Count);
                foreach (var entity in modules)
                {
                    map[entity.Code] = entity;
                }
                MemoryCache.Default.Set(R.CurrentUserOwnModulesMapCacheKey, map, DateTimeOffset.Now.AddHours(1));
                cacheObject = map;
            }

            var permissionMap = (Dictionary<string, SysModule>)cacheObject;
            if (permissionMap.Count == 0) return false;
            foreach (var code in codes)
            {
                var has = permissionMap.ContainsKey(code);
                if (!has)
                {
                    //任何一个为false,则直接返回false;
                    return false;
                }
            }
            return true;
        }

        #endregion

        /// <summary>
        /// 创建启动窗体
        /// </summary>
        public override Form OnCreateStartupForm()
        {
            SplashScreenHelper.Show("正在登录...");
            try
            {
                var isLogin = AsyncHelper.RunSync(LoginFormManager.AutoLoginAsync);
                if (isLogin)
                {
                    return OnCreateStartupFormCore();
                }
            }
            catch (System.Threading.Tasks.TaskCanceledException)
            {
                MessageBoxHelper.ShowWarn("连接到服务器超时,请检查网络!");
            }
            catch (HttpRequestException)
            {
                MessageBoxHelper.ShowWarn("连接到服务器失败,请检查网络!");
            }

            var frmLogin = CreateLoginForm();
            if (frmLogin.ShowDialog() != DialogResult.OK) return null;
            return OnCreateStartupFormCore();
        }

        private Form OnCreateStartupFormCore()
        {
            SplashScreenHelper.Show("正在创建主界面...");
            OnSysAppInit();
            var mainForm = CreateMainForm();
            SysApp.MainForm = mainForm;
            return mainForm;
        }

        /// <summary>
        /// 权限子系统系统初始化
        /// </summary>
        protected virtual void OnSysAppInit()
        {
            SysDicService.Instance.RefreshLocalCache();

            //配置权限
            AppDefaultSettings.AllowCustomLayoutControlSetting = App.Handler.Permit("sys.allowCustomLayoutControlSetting"); //是否允许自定义LayoutControl配置
            AppDefaultSettings.AllowCustomGridControlSetting = App.Handler.Permit("sys.allowCustomGridControlSetting");     //是否允许自定义GridControl配置
            AppDefaultSettings.AllowCustomTreeControlSetting = App.Handler.Permit("sys.allowCustomTreeControlSetting");     //是否允许自定义TreeControl配置
            AppDefaultSettings.AllowCustomChartControlSetting = App.Handler.Permit("sys.allowCustomChartControlSetting");   //是否允许自定义ChartControl配置
            AppDefaultSettings.AllowCustomWidgetSetting = App.Handler.Permit("sys.allowCustomWidgetSetting");               //是否允许自定义Widget配置
            AppDefaultSettings.AllowCustomReportDesign = App.Handler.Permit("sys.allowCustomReportDesign");                 //是否允许自定义设计报表

        }

        /// <summary>
        /// 创建主窗体
        /// </summary>
        public virtual Form CreateMainForm()
        {
            return new FrmStandardMain();
        }

        /// <summary>
        /// 创建主页窗口
        /// </summary>
        public virtual Form CreateLoginForm()
        {
            return new FrmStandardLogin();
        }

        /// <summary>
        /// 创建主页窗口
        /// </summary>
        public virtual Form CreateHomeForm()
        {
            return new FrmHome();
        }

        /// <summary>
        /// 创建关于窗口
        /// </summary>
        public virtual Form CreateAboutForm()
        {
            return new FrmAbout();
        }
    }
}